package com.bgy.config;

import com.bgy.common.base.ApiResult;
import com.bgy.common.enums.CodeMsg;
import com.bgy.common.exception.CommonException;
import com.bgy.common.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


/*/**
 * @Author donnie
 * @Description //TODO 全局捕获异常
 * @Date 2019-07-18 00:26
 **/
@Slf4j
@ControllerAdvice
public class ExceptionHandle {

    /**
     * 异常捕获
     *
     * @param exception 异常
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ApiResult exceptionHandle(Exception exception) {
        log.error("系统异常", exception);
        return ResultUtil.response(CodeMsg.FAILED);
    }

    /**
     * 通用异常捕获
     *
     * @param commonException 通用异常
     * @return
     */
    @ExceptionHandler(value = CommonException.class)
    @ResponseBody
    public ApiResult commonExceptionHandle(CommonException commonException) {
        log.error("通用异常:" + commonException.getMessage());
        return ResultUtil.response(commonException.getCode(), commonException.getMessage());
    }

    /**
     * 参数校验异常绑定
     *
     * @param bindException 绑定异常
     * @return
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public ApiResult bindExceptionHandle(BindException bindException) {
        StringBuilder msgBuilder = new StringBuilder();
        bindException.getFieldErrors().forEach(error -> msgBuilder.append(error.getField()).append(":")
                .append(error.getDefaultMessage()).append("/"));
        msgBuilder.deleteCharAt(msgBuilder.lastIndexOf("/"));
        String errorMsg = msgBuilder.toString();
        log.error("参数异常:" + errorMsg);
        return ResultUtil.response(CodeMsg.VALIDATE_PARAMETER.getCode(), errorMsg);
    }
}
